package com.ecoolex.ying.space.core.manager;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.RandomUtil;
import com.ecoolex.ying.space.core.dao.EstateProjectActivityCouponOrderDAO;
import com.ecoolex.ying.space.entity.EstateProjectActivityCoupon;
import com.ecoolex.ying.space.entity.EstateProjectActivityCouponOrder;
import com.ecoolex.ying.space.entity.EstateProjectActivityCouponOrder.Column;
import com.ecoolex.ying.space.entity.EstateProjectActivityCouponOrderExample;
import com.ecoolex.ying.space.entity.EstateProjectActivityCouponOrderExample.Criteria;
import com.ecoolex.ying.space.entity.PaymentOrder;
import com.ecoolex.ying.space.enums.EstateProjectActivityCouponOrderStatus;
import com.ecoolex.ying.space.enums.PaymentOrderStatus;
import com.ecoolex.ying.space.pojo.SubmitEstateProjectActivityCouponOrderDTO;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EstateProjectActivityCouponOrderManager {
	
    @Autowired
    private EstateProjectActivityCouponOrderDAO dao;
    
    @Autowired
    private EstateProjectActivityCouponManager couponManager;
    
    @Autowired
    private EstateProjectActivityCouponPackageManager packageManager;
    
    /**
     * 提交订单
     * @param submit
     * @param createUser
     * @return
     */
    public EstateProjectActivityCouponOrder submit(SubmitEstateProjectActivityCouponOrderDTO submit, String createUser) {
    	EstateProjectActivityCoupon activityCoupon = couponManager.getEstateProjectActivityCouponOnline(submit.getCouponId());
    	BizAssert.isTrue(Check.notNull(activityCoupon),ResultCode.VERIFY.build(10), "代金券不存在");
    	EstateProjectActivityCouponOrder order = new EstateProjectActivityCouponOrder();
    	order.setUserId(submit.getUserId());
    	order.setBuyNumber(submit.getBuyNumber());
    	order.setCouponId(submit.getCouponId());
    	order.setRealPrice(activityCoupon.getSalePrice().multiply(BigDecimal.valueOf(submit.getBuyNumber())));
    	order.setOrderNo(RandomUtil.randomInt(18));
    	order.setStatus(EstateProjectActivityCouponOrderStatus.UNPAID.real());
    	order.setDeleted(EstateProjectActivityCouponOrder.NOT_DELETED);
    	order.setCreateUser(createUser);
    	order.setCreateTime(Date.from(Instant.now()));
    	order.setUpdateUser(createUser);
    	order.setUpdateTime(Date.from(Instant.now()));
    	dao.insert(order);
    	return order;
    }
    
    /**
     * 支付成功后更新状态
     * @param paymentOrder
     * @param updateUser
     */
    @Transactional
    public void paySuccess(PaymentOrder paymentOrder,String updateUser) {
    	BizAssert.isTrue(PaymentOrderStatus.PAY_SUCCEED.real().equals(paymentOrder.getStatus()),
    		ResultCode.VERIFY.build(10), "未支付成功，无需处理");
    	EstateProjectActivityCouponOrder order = getByOrderNo(paymentOrder.getOrderNo());
    	BizAssert.isTrue(Check.notNull(order),ResultCode.VERIFY.build(11), "地产项目活动代金券订单不存在");
    	BizAssert.isTrue(EstateProjectActivityCouponOrderStatus.UNPAID.real().equals(order.getStatus()),
    		ResultCode.VERIFY.build(12), "订单必须在待支付时才能设置为已支付");
    	order.setTransNo(paymentOrder.getPaymentNo());
    	order.setPaymentTime(paymentOrder.getPaymentTime());
    	order.setStatus(EstateProjectActivityCouponOrderStatus.PAID.real());
    	order.setUpdateUser(updateUser);
    	order.setUpdateTime(Date.from(Instant.now()));
    	int row = dao.updateByPrimaryKeySelective(order, Column.transNo,
    										   Column.paymentTime,
    										   Column.status,
    										   Column.updateUser,
    										   Column.updateTime);	
    	BizAssert.isTrue(row == 1, ResultCode.BIZ.build(1), "设置已支付失败");
    	//给用户发代金券
    	packageManager.add(order, updateUser);
    }
    
    @Transactional
    public void refundSuccess(PaymentOrder paymentOrder,String updateUser) {
//    	BizAssert.isTrue(PaymentOrderStatus.REFUND_SUCCEED.real().equals(paymentOrder.getStatus()),
//    		ResultCode.VERIFY.build(10), "未退款成功，无需处理");
    	EstateProjectActivityCouponOrder order = getByOrderNo(paymentOrder.getOrderNo());
    	BizAssert.isTrue(Check.notNull(order),ResultCode.VERIFY.build(11), "地产项目活动代金券订单不存在");
    	//order.setTransNo(paymentOrder.getPaymentNo());
    	//order.setPaymentTime(paymentOrder.getPaymentTime());
    	//TODO 退款时间
    	order.setStatus(EstateProjectActivityCouponOrderStatus.REFUND.real());
    	order.setUpdateUser(updateUser);
    	order.setUpdateTime(Date.from(Instant.now()));
    	int row = dao.updateByPrimaryKeySelective(order, 
    										   Column.status,
    										   Column.updateUser,
    										   Column.updateTime);	
    	BizAssert.isTrue(row == 1, ResultCode.BIZ.build(1), "设置已退款失败");
    	//代金券退款
    	packageManager.refund(order, updateUser);
    }
    
    public void autoCancel(EstateProjectActivityCouponOrder order,String updateUser) {
    	BizAssert.isTrue(EstateProjectActivityCouponOrderStatus.UNPAID.equal(order.getStatus()),
    		ResultCode.VERIFY.build(10), "订单必须在待支付时才能取消");
    	EstateProjectActivityCouponOrderExample example = new EstateProjectActivityCouponOrderExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andOrderIdEqualTo(order.getOrderId())
    			.andStatusEqualTo(order.getStatus())
    			.andDeletedEqualTo(EstateProjectActivityCouponOrder.NOT_DELETED);
    	order.setStatus(EstateProjectActivityCouponOrderStatus.CANCEL.real());
    	order.setUpdateUser(updateUser);
    	order.setUpdateTime(Date.from(Instant.now()));
    	int row = dao.updateByExampleSelective(order, example, Column.status,Column.updateUser,Column.updateTime);
    	BizAssert.isTrue(row == 1,ResultCode.BIZ.build(1), "自动取消订单失败");
    }
    
    public EstateProjectActivityCouponOrder getByOrderId(Integer orderId,Integer userId) {
    	EstateProjectActivityCouponOrderExample example = new EstateProjectActivityCouponOrderExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andOrderIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(EstateProjectActivityCouponOrder.NOT_DELETED);
    	return dao.selectOneByExample(example);
    }
    
    public EstateProjectActivityCouponOrder getByOrderId(Integer orderId) {
		return dao.selectByPrimaryKeyWithLogicalDelete(orderId, EstateProjectActivityCouponOrder.NOT_DELETED);
	}
    
    public EstateProjectActivityCouponOrder getByOrderNo(String orderNo) {
    	EstateProjectActivityCouponOrderExample example = new EstateProjectActivityCouponOrderExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andOrderNoEqualTo(orderNo).andDeletedEqualTo(EstateProjectActivityCouponOrder.NOT_DELETED);
    	return dao.selectOneByExample(example);
    }
    
    /**
     * 查询待支付且过期的订单
     * @param expirationTime
     * @param size
     * @return
     */
    public List<EstateProjectActivityCouponOrder> getUnpaidAndExpiration(Date expirationTime,int size){
    	EstateProjectActivityCouponOrderExample example = new EstateProjectActivityCouponOrderExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andStatusEqualTo(EstateProjectActivityCouponOrderStatus.UNPAID.real())
    			.andCreateTimeLessThan(expirationTime)
    			.andDeletedEqualTo(EstateProjectActivityCouponOrder.NOT_DELETED);
    	example.orderBy(Column.createTime.asc());
    	example.limit(size);
    	return dao.selectByExample(example);
    }
}